<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item><router-link to="/financialCenter/fundAccountManagement">资金账户管理</router-link></a-breadcrumb-item>
        <a-breadcrumb-item>资金明细</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="pageContentWhole">
      <a-row :gutter="[16]">
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="交易类型">
              <a-select v-model="searchForm.typeId" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in transactionTypes" :key="v.dictionaryId">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="交易摘要">
              <a-input v-model="searchForm.remark"></a-input>
            </a-form-item>
            <a-form-item label="交易日期">
              <a-range-picker @change="onChange"><a-icon slot="suffixIcon" type="calendar" /></a-range-picker>
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="addItem">+  添加交易记录</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="importData">批量导入</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="excelExport">导出Excel</a-button>
            </a-form-item>
          </a-form>

          <a-card style="text-align:center; margin-top:24px;">
            <a-col :span="6" class="assent">
              <div class="assent_mes">当前余额</div>
              <div class="assent_shu">{{capitalAccountStatistics.balance||0}}</div>
            </a-col>
            <a-col :span="6" class="assent">
              <div class="assent_mes">交易笔数</div>
              <div class="assent_shu">{{capitalAccountStatistics.transactionCount||0}}</div>
            </a-col>
            <a-col :span="6" class="assent">
              <div class="assent_mes">收入总金额</div>
              <div class="assent_shu">{{capitalAccountStatistics.totalIncomeAmount||0}}</div>
            </a-col>
            <a-col :span="6">
              <div class="assent_mes">支出总金额</div>
              <div class="assent_shu">{{capitalAccountStatistics.totalPayAmount||0}}</div>
            </a-col>
          </a-card>

          <a-table :columns="columns" :data-source="tableData" :loading="loading" class="tableMargin" :pagination="pagination" rowKey="id">
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="operation" slot-scope="text, record">
                <a @click="editIt(record)">编辑</a>
                <a @click="deleteIt(record.id)">删除</a>
              </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 添加/编辑 -->
    <a-modal :visible="visible" :title="title" :confirmLoading="confirmLoading"
      :destroyOnClose="true" :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
      >
      <a-form-model
        ref="rulesForm"
        :model="form" :label-col="labelCol" :wrapper-col="wrapperCol"
        :rules="rules">
        <a-form-model-item label="收入金额" prop="incomeAmount">
          <a-input-number :min="0" :precision="2" :max="999999999999.99" v-model="form.incomeAmount" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="支出金额" prop="payAmount">
          <a-input-number :min="0" :precision="2" :max="999999999999.99" v-model="form.payAmount" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="交易后余额" prop="balance">
          <a-input-number :min="0" :precision="2" :max="999999999999.99" v-model="form.balance" style="width: 100%"></a-input-number>
        </a-form-model-item>
        <a-form-model-item label="交易类型" prop="typeId">
          <a-select v-model="form.typeId" class="selectWidth">
            <a-select-option key>请选择</a-select-option>
            <a-select-option v-for="v in transactionTypes" :key="v.dictionaryId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="交易摘要">
          <a-input v-model="form.remark" ></a-input>
        </a-form-model-item>

        <a-form-model-item label="交易日期" prop="transactionDate">
          <a-date-picker v-model="form.transactionDate"><a-icon slot="suffixIcon" type="calendar" /></a-date-picker>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 导入记录 -->
    <a-modal
      width="900px"
      :visible="visible2" title="导入记录" :confirmLoading="confirmLoading"
      centered destroyOnClose :maskClosable="false"
      @ok="handleOk2"
      @cancel="handleCancel2">
        <a-form-model
        ref="form2"
        :label-col="{span:2}"
        :wrapper-col="{span:10}"
        style="margin-top:20px">
          <a-form-model-item label="上传数据" :wrapper-col="{span:14}">
          <a-row>
            <a-col :span="17">
              <a-upload-dragger
                accept=".xls, .xlsx"
                :action="uploadUrl"
                :headers="headers"
                :beforeUpload="beforeUpload"
                :file-list="fileList"
                @change="handleChange"
              >
                <p class="ant-upload-drag-icon">
                  <a-icon type="inbox" />
                </p>
                <p class="ant-upload-text">上传Excel文件</p>
              </a-upload-dragger>
            </a-col>
            <a-col :span="3" :offset="1">
              <a-button ghost type="primary" @click="download" style="margin-top:95px">下载模板</a-button>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item v-if="billInfo" label="检测结果" :wrapper-col="{span:14}">
          <a-row>
            <a-col :span="17">
              <a-list size="large" bordered>
                <a-list-item>
                  当前余额
                  <span class="orange">{{billInfo.totalBalance}}</span>
                </a-list-item>
                <a-list-item>
                  交易笔数
                  <span class="orange">{{billInfo.transactionCount}}</span>
                </a-list-item>
                <a-list-item>
                  收入总金额
                  <span class="orange">{{billInfo.totalIncomeAmount}}</span>
                </a-list-item>
                <a-list-item>
                  支出总金额
                  <span class="orange">{{billInfo.totalPayAmount}}</span>
                </a-list-item>
              </a-list>
            </a-col>
          </a-row>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import {queryDataDictionaryList} from '@/api'
import { commonExport, importFile } from '@/api/request'
import {queryCapitalAccountDetail, addCapitalAccountDetail, updateCapitalAccountDetail, deleteCapitalAccountDetail} from '@/api/financialCenter'
import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'
import store from 'store'
import md5 from 'md5'
import Util from '@/common/util'

const fomrMessage = `必填项不能为空`
const defaultForm = (capitalAccountId) => {
  return {
    capitalAccountId,
    id: null,
    incomeAmount: '',
    payAmount: '', // 支出金额
    balance: '', // 交易后余额
    typeId: '', // 交易类型id
    remark: '', // 交易摘要
    transactionDate: ''
  }
}

export default {
  props: ['id'],
  data () {
    const columns = [
      {
        title: '序号',
        width: 60,
        scopedSlots: {customRender: 'rn'}
      },
      {
        title: '收入金额',
        dataIndex: 'incomeAmount'
      },
      {
        title: '支出金额',
        dataIndex: 'payAmount'
      },
      {
        title: '交易后余额',
        dataIndex: 'balance'
      },
      {
        title: '交易类型',
        dataIndex: 'transactionName'
      },
      {
        title: '交易摘要',
        dataIndex: 'remark',
        ellipsis: true,
        customRender: (text, row, index) => {
          return text || '--'
        }
      },
      {
        title: '交易日期',
        dataIndex: 'transactionDate'
      },
      {
        title: '操作',
        width: 160,
        scopedSlots: {customRender: 'operation'}
      }
    ]

    return {
      transactionTypes: [],
      searchForm: {
        capitalAccountId: this.id,
        typeId: '',
        remark: '',
        searchStartTime: '',
        searchEndTime: ''
      },
      capitalAccountStatistics: {},
      columns,
      tableData: [],
      loading: false,
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // modal
      labelCol: {span: 8},
      wrapperCol: {span: 14},
      visible: false,
      title: '',
      confirmLoading: false,
      form: defaultForm(this.id),
      rules: {
        incomeAmount: [{required: true, message: fomrMessage, trigger: 'blur'}],
        payAmount: [{required: true, message: fomrMessage, trigger: 'blur'}], // 支出金额
        balance: [{required: true, message: fomrMessage, trigger: 'blur'}], // 交易后余额
        typeId: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}], // 交易类型id
        remark: [{required: true, message: fomrMessage, trigger: 'blur'}], // 交易摘要
        transactionDate: [{required: true, message: fomrMessage, trigger: ['blur', 'change']}]
      },
      // 导入
      visible2: false,
      billInfo: null,
      fileList: [],
      headers: {},
      file: {},
      uploadUrl: REQUEST_INTEFACE_URL + '/bill/previewImportAccountDetail'
    }
  },
  methods: {
    onChange (data, dateString) {
      this.searchForm.searchStartTime = dateString[0]
      this.searchForm.searchEndTime = dateString[1]
    },
    excelExport () {
      commonExport('/bill/exportCapitalAccountDetail', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    },
    // 导入
    importData () {
      if (!this.$root._bc.importDetail) {
        this.$message.error('您无此权限！')
        return
      }
      this.fileList = []
      this.file = {}
      this.billInfo = null
      this.visible2 = true
    },
    download () {
      commonExport('/common/downloadExcelTemplate', {
        name: '资金账户导入模板.xls'
      })
    },
    beforeUpload (file) {
      let self = this
      let fileLength = self.fileList.length
      let capitalAccountId = this.id
      return new Promise((resolve, reject) => {
        if (capitalAccountId) {
          if (fileLength > 0) {
            self.$message.error('Excel文件已存在！')
            reject(new Error(false))
          } else {
            const uuid = Util.getUUID()
            const headers = {
              appKey: APP_KEY,
              version: VERSION_NO,
              timestamp: (() => new Date().getTime())(),
              nonce: uuid,
              token: store.get('token') ? store.get('token') : '',
              sign: md5(`appKey${APP_KEY}nonce${uuid}timestamp${new Date().getTime()}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase(),
              capitalAccountId: capitalAccountId
            }
            self.headers = headers
            resolve()
          }
        } else {
          reject(new Error(false))
        }
      })
    },
    handleOk2 () {
      if (this.fileList && this.fileList.length === 1) {
        let formData = new FormData()
        formData.append('capitalAccountId', this.id)
        formData.append('file', this.file.originFileObj)
        importFile(formData).then(rsp => {
          this.visible2 = false
          this.handleSubmit()
        })
      } else {
        this.$message.error('请先上传excel文件')
      }
    },
    handleCancel2 () {
      this.visible2 = false
    },
    handleChange ({ file, fileList }) {
      this.fileList = fileList
      this.file = file
      if (file.status === 'done') {
        if (file.response.code === 0) {
          this.billInfo = file.response.data
        } else {
          this.$message.error(file.response.message)
        }
      } else if (file.status === 'removed') {
        this.billInfo = null
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.loading = true
      queryCapitalAccountDetail({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.capitalAccountDetailList.list
        this.capitalAccountStatistics = rsp.data.capitalAccountStatistics
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.capitalAccountDetailList.pageSize,
          total: rsp.data.capitalAccountDetailList.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.capitalAccountDetailList.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      }).catch(() => { this.loading = false })
    },
    // 添加
    addItem () {
      if (!this.$root._bc.createDetail) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = defaultForm(this.id)
      this.title = '添加交易记录'
      this.visible = true
    },
    // 编辑
    editIt (item) {
      if (!this.$root._bc.editDetail) {
        this.$message.error('您无此权限！')
        return
      }
      this.form = {...item, capitalAccountId: this.id}
      this.title = '编辑交易记录'
      this.visible = true
    },
    handleOk () {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          const data = Object.assign({}, this.form, {transactionDate: this.form.transactionDate.format ? this.form.transactionDate.format('YYYY-MM-DD') : this.form.transactionDate})
          if (!this.form.id) {
            addCapitalAccountDetail(data).then(rsp => {
              this.$message.success('添加成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          } else {
            updateCapitalAccountDetail(data).then(rsp => {
              this.$message.success('编辑成功')
              this.visible = false
              this.handleSubmit()
              setTimeout(() => { this.confirmLoading = false }, 1000)
            }).catch(() => { this.confirmLoading = false })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false
    },
    deleteIt (id) {
      if (!this.$root._bc.dropDetail) {
        this.$message.error('您无此权限！')
        return
      }
      const _t = this
      this.$confirm({
        title: '删除交易记录后将影响金额统计，确认删除？',
        onOk () {
          deleteCapitalAccountDetail({id}).then(rsp => {
            _t.$message.success('删除成功')
            _t.handleSubmit()
          })
        }
      })
    }
  },
  created () {
    // 选择所有交易类型字典
    queryDataDictionaryList({
      type: 'TRANSACTION_TYPE',
      status: 1,
      pageNum: 1,
      pageSize: 999
    }).then(rsp => {
      this.transactionTypes = rsp.data.list
    })
  },
  mounted () {
    this.handleSubmit()
  }
}
</script>

<style lang="less" scoped>
</style>
